package com.bjpowernode.crm.web.listener;


import com.bjpowernode.crm.pojo.Value;
import com.bjpowernode.crm.service.ValueService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.*;

@WebListener
public class InitCache implements ServletContextListener {
    @Autowired
    private ValueService  valueService;
    @Override
    public void contextInitialized(ServletContextEvent sce) {//实现初始化方法
        //获取spring创建好的工厂对象
        WebApplicationContext factory = ContextLoader.getCurrentWebApplicationContext();
        ValueService valueService = factory.getBean(ValueService.class);
        //调用获取数据字典的业务逻辑层：返回一个数据字典集合
        List<Value> dicList = valueService.getAll();

        // Map<字典类型, 类型对应的集合>
        Map<String, List> dicMap = new HashMap<>();

        for (Value v : dicList) {
            List list = dicMap.get(v.getTypeCode());
            if (list == null) {
                list = new ArrayList();
                dicMap.put(v.getTypeCode(), list);
            }
            list.add(v);
        }
        //将这个集合存到ServletContext作用域中，作为服务器缓存
        sce.getServletContext().setAttribute("dicMap",dicMap);
        System.out.println(dicMap);
        //前端就通过 dicList 获取数据，根据属性 字典数据类型 来选择展示不同的下拉选


        //将stage与对应的可能行存到服务器缓存中:前端依然是通过获取map集合的key来获取对应的value
        Map stages = new HashMap();
        //读取配置文件：stage.properties
        ResourceBundle resourceBundle = ResourceBundle.getBundle("stage");
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()){//遍历结果集，如果有值，则进入循环取值
            String key = keys.nextElement();
            String value = resourceBundle.getString(key);
            //将key=value存入我们声明的集合:key就是中文，value就是我们设置的可能性
            stages.put(key, value);
        }
        //将集合以json对象返回给前台：{属性key=value值，属性key2=value值2...}
        ObjectMapper om = new ObjectMapper();
        try {
            String json = om.writeValueAsString(stages);
            //将json对象存到服务器内存中，服务器一启动就创建好，随时用
            sce.getServletContext().setAttribute("stages",json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }








        //将所有阶段单独存到缓存中
        try {
            String json2 = om.writeValueAsString(dicMap.get("stage"));
            sce.getServletContext().setAttribute("stage",json2);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }
}
